import './presetVar'
import requestApi from "ssccommon/components/requestApi";
import _ from 'lodash-es'
import {ajax,toast } from 'nc-lightapp-front';
import { getRequest1 } from './initTemplate'
import {beforeUpdatePage, updatePage} from 'ssccommon/utils/updatePage';
import logs from 'ssccommon/utils/logs';
import presetVar from "../../adjustment/card/presetVar";
import attachments from 'uap/common/components/getAttachmentInfo';
const { getAttachments, getAttachmentsInfo } = attachments;

let debugLogs = new logs();
let requestDomain =  '';
let referResultFilterCondition='';
let requestApiOverwrite = {
    ...requestApi,
    //单据模板接口
    tpl: (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountTempletAction.do`,
            data: opt.data,
            success: opt.success
        });
    },
    loaddata:(opt) => {
        let props = opt.props;
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountDefDataAction.do?uistatus=add&tradetype=`+window.presetVar.tradetype,
            data: opt.data,
            success: (data) => {
                console.timeEnd('请求：loadData耗时');
                console.time('meta第2次设置耗时');
                // TOP 性能优化，增加统一刷新方法 chengwbc ADD
                beforeUpdatePage(props);
                // BTM 性能优化，增加统一刷新方法
                // data = data.data;
                // let newData = {}
                // newData.head = data.data.head.head;
                // newData.body = data.data.bodys[0].body;
                if(data.data.userjson && JSON.parse(data.data.userjson)){
                    let djlx = JSON.parse(data.data.userjson);
                    if(djlx && djlx.ISCONTRAST && djlx.jkyjye && djlx.jkyjye >0){//是否冲借款
                        window.presetVar["ISCONTRAST"]=djlx.ISCONTRAST;
                    }
                    if(djlx && djlx.IS_MACTRL){//是否冲借款
                        window.presetVar["IS_MACTRL"]=djlx.IS_MACTRL;
                    }
                }
                //referResultFilterCondition = JSON.parse(JSON.parse(data.data.userjson).crossrule);//交叉校验规则设置
                window.presetVar.reimsrc = JSON.parse(data.data.userjson).reimsrc?JSON.parse(JSON.parse(data.data.userjson).reimsrc):null;//核心控制项-影响因素
                window.presetVar.showitemkey = JSON.parse(data.data.userjson).showitemkey;//显示项
                window.presetVar.reimruleitemkeys = JSON.parse(data.data.userjson).reimruleitemkeys;//报销标准涉及字段
                window.presetVar.ratecontorl = JSON.parse(data.data.userjson).RATECONTORL//集团参数NC004“组织汇率是否可编辑
                window.presetVar.zzbwb = JSON.parse(data.data.userjson).ZZBWB//组织币种
                setMetasInit(opt.meta,props,data.data);
                opt.success(data.data, opt.meta);
                // TOP 性能优化，增加统一刷新方法 chengwbc ADD
                // let ls_bodys = [];
                // Object.values(window.presetVar.body).forEach((body)=>{
                //     ls_bodys.push(body);
                // });
                // updatePage(props, 'head', ls_bodys);
                // BTM 性能优化，增加统一刷新方法
            }
        })
    },
    //获取reimsrc 获取控制项
    loadReimsrc:(opt) => {
        let props = opt.props;
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountDefDataAction.do?uistatus=add&tradetype=`+window.presetVar.tradetype,
            data: opt.data,
            success: (data) => {
                console.timeEnd('请求：loadReimsrc耗时');
                console.time('meta第2次设置耗时');

                window.presetVar.reimsrc = JSON.parse(data.data.userjson).reimsrc?JSON.parse(JSON.parse(data.data.userjson).reimsrc):null;//核心控制项-影响因素
                // window.presetVar.showitemkey = JSON.parse(data.data.userjson).showitemkey;//显示项
                window.presetVar.reimruleitemkeys = JSON.parse(data.data.userjson).reimruleitemkeys;//报销标准涉及字段

            }
        })
    },
    savejkbx:(opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountSaveAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                if(data.success=='false'){
                    let toastType = 'danger';
                    if (data.control) {
                        if (data.control == 'Y') { // 预算柔性控制
                            toastType = 'danger'; // 警告类型的taast不会自动消失。
                        } else if (data.message && data.message.length > 40) {
                            toastType = 'danger';
                        } else {
                            toastType = 'warning';
                        }
                    }
                    toast({content:data.message || '未知错误',color: toastType});
                    return;
                }

                opt.success(data);
            },
            error:(data)=>{
                toast({content:data.message,color:'danger'});
            }
        })
    },
    valueChange:(opt) => {

        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountValueChangeAction.do`,
            data: opt.data,
            async:false,
            success: (data) => {
                data = data.data;
                const userjson = JSON.parse(data.userjson)
                if(userjson.errormsg) {
                    toast({content: userjson.errormsg, color:'danger'})
                }
                opt.success(data);
            }
        })
    },
    viewBill:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountViewAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                //报销标准带出
                window.presetVar.reimsrc = JSON.parse(data.userjson).reimsrc?JSON.parse(JSON.parse(data.userjson).reimsrc):null; //核心控制项-影响因素
                window.presetVar.showitemkey = JSON.parse(data.userjson).showitemkey;//显示项
                window.presetVar.reimruleitemkeys = JSON.parse(data.userjson).reimruleitemkeys;//报销标准涉及字段
                window.presetVar.ratecontorl = JSON.parse(data.userjson).RATECONTORL//集团参数NC004“组织汇率是否可编辑
                window.presetVar.zzbwb = JSON.parse(data.userjson).ZZBWB//组织币种
                const isPropt = JSON.parse(data.userjson).prompt;
                if(isPropt) {
                    const msg = JSON.parse(data.userjson).reimmsg;
                    toast({content:msg,color:'danger'});
                }
                if(opt.meta) {
                    //对meta进行过滤
                    opt.meta['head'].items.forEach((item) => {
                        if(item.itemtype == 'refer'){
                            //处理交叉校验规则和参照过滤
                            filterAllRefParm(item, opt.props, 'head');
                        }
                    });

                    for (let tablecode in opt.meta.gridrelation) {
                        opt.meta[tablecode].items.forEach(item => {
                            if(item.itemtype == 'refer' && item.visible == true){
                                //处理交叉校验规则和参照过滤
                                filterAllRefParm(item, opt.props, tablecode);
                            }
                        })
                    }

                }
                opt.success(data);
            },
            // error:(data) =>{
            //     debugger
            //     toast({content:data.message,color:'warning'});
            // }
        });
    },
    copyBill:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountCopyAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            }
        });
    },
    submitBill:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountSubmitAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                if(data.success!=undefined&&data.success=='false'){
                    let toastType = 'danger';
                    if (data.control) {
                        if (data.control == 'Y') { // 预算柔性控制
                            toastType = 'danger'; // 警告类型的taast不会自动消失。
                        } else if (data.message && data.message.length > 40) {
                            toastType = 'danger';
                        } else {
                            toastType = 'warning';
                        }
                    }
                    toast({content:data.message || '未知错误',color: toastType});
                    return;
                }
                opt.success(data);
            },
            // error:(data) =>{
            //     toast({content:data.message,color:'danger'});
            // }
        });
    },
    generatBillId:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/action/generatBillId.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'danger'});
            }
        });
    },
    BillCjk:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountCjkAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'danger'});
            }
        });
    },
    transfer2Table: (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountInvoiceToBxbodyAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'danger'});
            }
        })
    }
    ,BillFyyt:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountFyytAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'danger'});
            }
        });
    },
    billRecall:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountRecallAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'danger'});
            }
        });
    },
    deleteBill:(opt)=>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountDeleteAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'danger'});
            }
        });
    },
    billInvalid:(opt)=>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountInvalidBillAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'danger'});
            }
        });
    },
    queryextend:(opt)=>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountExtendAttrAction.do`,
            data: opt.data,
            async:false,
            success: (data) => {
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'danger'});
            }
        });
    },
    getUnEditAttributes:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/pub/ErmAttributeEditableAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'danger'});
            }
        });
    },
    makebill: (opt) => {
        let srcAppcode ='201102CBSP';
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/makebill/MakeBillJKBXAction.do`,
            data: opt.data,
            success: (res) => {
                console.log('接口返回数据：', res);
                let { data } = res;
                if (!data) {
                    return;
                }
                //let srccode = srcAppcode + '_MadeBill2019';
                //cacheTools.set(srcAppcode + '_MadeBill2019',data.pklist);
                //let srccode = srcAppcode + res.data.cachekey;
               // cacheTools.set(srcAppcode + res.data.cachekey, data.pklist);




                opt.success(data);
            },
            error: (data) => {
                toast({ content: data.message, color: 'danger' });
            }
        })
    },
    handleLoadDataResDada:(meta,props,moudleid) =>{
       handleLoadDataResDada(meta,props,moudleid)
    },
    filterAllRefParm:(item,props,moudleid) =>{
        filterAllRefParm(item,props,moudleid)
    },
    setbodyinitvalue:(metas,headrows)=>{
        setbodyinitvalue(metas,headrows)
    },
    filterDatas:(data) =>{
        return filterDatas(data)
    },
    setMetasInit:(meta,props,data)=>{
        setMetasInit(meta,props,data)
    },
    billShare:(opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/JkbxBillShareAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            },
            error:(data)=>{
                toast({content:data.message,color:'danger'});
            }
        })
    },
    delete3status:(billdata)=>{
        delete3status(billdata)
    },
    linkqueryjsd:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountLinkJsAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            },
            error:(data)=>{
                toast({content:data.message,color:'danger'});
            }
        })
    },

    /**
     * 判断该附件是否可删除
    */
   canDelete:(opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erminvoice/DeleteBeforeCheckAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            },
            error:(data)=>{
                toast({content:data.message,color:'danger'});
            }
        })
   },

   /**
    * 获取控制附件修改和必须上传的接口
    */
   getAttachmentControlParams: (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/ermextendattr/ErmAccessoryControl.do`,
            data: opt.data,
            success: (response) => {
                const data = response.data
                if (data && data.success) {
                    opt.success(data);
                } else {
                    toast({content:data.message,color:'danger'});
                }
            },
            error:(data)=>{
                toast({content:data.message,color:'danger'});
            }
        })
   },

   /**
    * 判断附件是否已经上传
    */
   isAttachmentsUploaded: async (billId) => {
        const count = await getAttachments(billId)
        return count > 0
   }
}

async function isUploadedAttachments(props) {
    const billId = props.getUrlParam('billid') || props.getUrlParam('id') || this.state.billId || "";
    //附件控制必传
    if (window.presetVar.attachmentControl && window.presetVar.attachmentControl.necessary) {
        if (!billId) {
            toast({content:"必须上传附件",color:'danger'})
            return false
        }
        const hasUploaded = await requestApiOverwrite.isAttachmentsUploaded(billId)
        if (hasUploaded) {
            return true
        } else {
            toast({content:"必须上传附件",color:'danger'})
            return false
        }
    }
    return true
}

function  delete3status(data){
    if(data.bodys){
        for(let bodyName in data.bodys){
            let filterrow =[];
            if(data.bodys[bodyName].rows){
                data.bodys[bodyName].rows.map((one)=>{
                    if(one.status!='3'){
                        filterrow[filterrow.length]=one;
                    }
                })
            }
            data.bodys[bodyName].rows = filterrow;
        }
    }
}
function setMetasInit(meta,props,data){
    let headValues = data.head[presetVar.head.head1].rows[0].values;
    window.presetVar.reloadHead = data.head[presetVar.head.head1];
    window.presetVar.headValuesAll = headValues;
    data.head['head'].rows.forEach((row) => {
        for (let attrCode in row.values) {
            let initialvalue = {
                value : row.values[attrCode].value,
                display: row.values[attrCode].display,
                scale: row.values[attrCode].scale
            };
            meta['head'].items.forEach((item) => {
                if (item.attrcode == attrCode && attrCode.indexOf('.')<0) {
                    item.initialvalue = initialvalue;
                    // TOP 性能优化，不显示的数据不用添加参照过滤条件 chengwbc MOD
                    // if(item.itemtype == 'refer'){
                    if(item.itemtype == 'refer' && item.visible == true){
                    // BTM 性能优化，不显示的数据不用添加参照过滤条件
                        //处理交叉校验规则和参照过滤
                        filterAllRefParm(item,props, 'head');
                    }
                    if(item.itemtype == "number"){
                        item.replacehoder=0;
                    }
                }
            });
            _.get(meta, 'formrelation.head', []).forEach(key => {
                meta[key].items.forEach((item) => {
                    if (item.attrcode == attrCode && attrCode.indexOf('.')<0) {
                        item.initialvalue = initialvalue;
                        // TOP 性能优化，不显示的数据不用添加参照过滤条件 chengwbc MOD
                        // if(item.itemtype == 'refer'){
                        if(item.itemtype == 'refer' && item.visible == true){
                        // BTM 性能优化，不显示的数据不用添加参照过滤条件
                            //处理交叉校验规则和参照过滤
                            filterAllRefParm(item,props, 'head');
                        }
                        if(item.itemtype == "number"){
                            item.replacehoder=0;
                        }
                    }
                });
            })
        }
    });
    // TOP 性能优化，多层循环逻辑变更 chengwebc MOD
    // for(let body in data.bodys){
    //     if(data.bodys[body] && data.bodys[body].rows && data.bodys[body].rows.length>0){
    //         // TOP 性能优化，所有meta相关修改无需按行处理，取第一行即可 MOD
    //         // data.bodys[body].rows.forEach((row) => {
    //             let row = data.bodys[body].rows[0];
    //         // BTM 性能优化，所有meta相关修改无需按行处理，取第一行即可
    //             for (let attrCode in row.values){
    //                 let initialvalue = {
    //                     value: row.values[attrCode].value,
    //                     display: row.values[attrCode].display,
    //                     scale: row.values[attrCode].scale
    //                 };
    //                 for (let table in meta.gridrelation) {
    //                     meta[table].items.forEach((item) => {
    //                         if(item.attrcode=='tablecode'){
    //                             let itvalue = {
    //                                 value:table,
    //                                 display:table
    //                             }
    //                             item.initialvalue = itvalue;
    //                         }
    //                         // if(item.itemtype == 'refer'){
    //                         //     item.visible = true;//zheli fangkai
    //                         //     item.disabled = false;
    //                         // }
    //                         if (item.attrcode == attrCode && attrCode.indexOf('.')<0){
    //                             item.initialvalue = initialvalue;
    //                             // TOP 性能优化，参照过滤设置先判断是否需要设置 chengwebc MOD
    //                             // filterAllRefParm(item,props,table);
    //                             if(item.itemtype == 'refer' && item.visible == true){
    //                                 filterAllRefParm(item, props, table);
    //                             }
    //                             // BTM 性能优化，参照过滤设置先判断是否需要设置
    //                         }
    //                     });
    //                     meta[table+"&childform2"].items.forEach((item) => {
    //                         if (item.attrcode == attrCode&&item.itemtype == 'refer') {
    //                             if(item.attrcode=='tablecode'){
    //                                 let itvalue = {
    //                                     value:table,
    //                                     display:table
    //                                 }
    //                                 item.initialvalue = itvalue;
    //                             }
    //                             if (item.attrcode == attrCode && attrCode.indexOf('.')<0){
    //                                 item.initialvalue = initialvalue;
    //                                 // let filterCondition = referResultFilterCondition[table+"&childform2"][item.attrcode];
    //                                 // if (filterCondition) {
    //                                 //     item.referFilterAttr = {[item.attrcode] :  filterCondition};
    //                                 // }
    //                             }
    //                         }
    //                         // TOP 性能优化，参照过滤设置先判断是否需要设置 chengwebc MOD
    //                         // filterAllRefParm(item,props,table);
    //                         if(item.itemtype == 'refer' && item.visible == true){
    //                             filterAllRefParm(item,props,table);
    //                         }
    //                         // BTM 性能优化，参照过滤设置先判断是否需要设置
    //                     });
    //                 }
    //             }
    //         // TOP 效率问题修改，所有meta相关修改无需按行处理，取第一行即可 DEL
    //         // });
    //         // BTM 效率问题修改，所有meta相关修改无需按行处理，取第一行即可
    //     }else{
    //         setbodyinitvalue(meta,data.head['head'].rows[0].values);
    //     }
    // }
    let bodyInitialvalue = {};
    for(let body in data.bodys){
        ((data.bodys[body] || {}).rows || {}).length>0 && (bodyInitialvalue[body] = data.bodys[body].rows[0].values);
    }

    let numberInitialvalueField = ['bbhl','tax_rate','groupbbhl','globalbbhl','rowno'];
    for (let table in meta.gridrelation) {
        let tablecode = meta[table].items.find(e=>e.attrcode === 'tablecode');
        if(tablecode){
            tablecode.initialvalue = {
                value:table,
                display:table
            }
        }else{
            meta[table].items.push({
                attrcode: 'tablecode',
                visible: false,
                initialvalue: {
                    value:table,
                    display:table
                }
            })
        }
        if(bodyInitialvalue[table]){
            meta[table].items.forEach((item) => {
                if (item.attrcode && item.attrcode.indexOf('.') < 0 && bodyInitialvalue[table][item.attrcode]) {
                    if ((item.itemtype != 'number' || numberInitialvalueField.indexOf(item.attrcode) >= 0 || item.attrcode == window.presetVar.showitemkey || (window.presetVar.reimsrc && window.presetVar.reimsrc.indexOf(item.attrcode) >= 0))) {
                        item.initialvalue = {
                            value: bodyInitialvalue[table][item.attrcode].value,
                            display: bodyInitialvalue[table][item.attrcode].display,
                            scale: bodyInitialvalue[table][item.attrcode].scale,
                        };
                    } else {
                        item.initialvalue = {
                            // TOP 金额字段不需要显示默认值 chengwebc DEL
                            // value: bodyInitialvalue[table][item.attrcode].value,
                            // display: bodyInitialvalue[table][item.attrcode].display,
                            // BTM 金额字段不需要显示默认值
                            //20190510 去掉该代码：解决表体精度问题
                            scale: bodyInitialvalue[table][item.attrcode].scale
                        };
                        //干掉：后台自定义项未初始化类型 影响精度
                        // item.scale = (bodyInitialvalue[table][item.attrcode] || {scale:-1}).scale;
                    }
                }
                if(item.itemtype == 'refer' && item.visible == true){
                    filterAllRefParm(item, props, table);
                }
            })

            if(!meta[table+"&childform2"]){
                toast({content:'单据模板缺少表体配置childform2', color:'danger'})
            }
            meta[table+"&childform2"] && meta[table+"&childform2"].items.forEach((item) => {
                if (item.attrcode && item.attrcode.indexOf('.') < 0 && bodyInitialvalue[table][item.attrcode]) {
                    if ((item.itemtype != 'number' || numberInitialvalueField.indexOf(item.attrcode) >= 0)) {
                        item.initialvalue = {
                            value: bodyInitialvalue[table][item.attrcode].value,
                            display: bodyInitialvalue[table][item.attrcode].display,
                            scale: bodyInitialvalue[table][item.attrcode].scale,
                        };
                    } else {
                        item.initialvalue = {
                            // TOP 金额字段不需要显示默认值 chengwebc DEL
                            //  value: bodyInitialvalue[table][item.attrcode].value,
                            //  display: bodyInitialvalue[table][item.attrcode].display,
                            // BTM 金额字段不需要显示默认值
                            scale: bodyInitialvalue[table][item.attrcode].scale
                        };
                        // item.scale = (bodyInitialvalue[table][item.attrcode] || {scale:-1}).scale;
                    }
                }
                if(item.itemtype == 'refer' && item.visible == true){
                    filterAllRefParm(item,props,table);
                }
            });
        }else{
            setbodyinitvalue(meta,data.head['head'].rows[0].values);
            meta[table].items.forEach((item) => {
                if(item.itemtype == 'refer' && item.visible == true){
                    filterAllRefParm(item, props, table);
                }
            })
            meta[table+"&childform2"].items.forEach((item) => {
                if(item.itemtype == 'refer' && item.visible == true){
                    filterAllRefParm(item,props,table);
                }
            });
        }
    }
    // BTM 性能优化，多层循环逻辑变更
}

export {
    setMetasInit,
    isUploadedAttachments
}

function handleLoadDataResDada(meta, props,moduleId) {
    if(data.data.head[presetVar.head.head1].rows[0])
    {
        let headValues = data.data.head[presetVar.head.head1].rows[0].values;
        for (let attrcode in headValues) {
            meta[presetVar.head.head1].items.forEach((item) => {
                if (item.attrcode == attrcode) {
                    item.initialvalue = {
                        value: headValues[attrcode].value,
                        display: headValues[attrcode].display=null?headValues[attrcode].value:headValues[attrcode].display
                    };


                    //处理交叉校验规则和参照过滤
                    filterAllRefParm(item,props, moduleId);
                }

            });
        }
    }

    //适配多表头
    if (meta.formrelation) {
        let headValues = data.data.head[presetVar.head.head1].rows[0].values;
        meta.formrelation[presetVar.head.head1].forEach((item) => {
            if (meta[item]) {
                meta[item].items.forEach((key) => {
                    let attrcode = key.attrcode;
                    if (headValues[attrcode]) {
                        key.initialvalue = {
                            value: headValues[attrcode].value,
                            display: headValues[attrcode].display=null?headValues[attrcode].value:headValues[attrcode].display
                        };
                        //处理交叉校验规则和参照过滤
                        filterAllRefParm(key, props, presetVar.head.head1);
                    }
                })
            }

        });
    }
    Object.keys(presetVar.body).forEach((bodyindex) =>{
        let bodyname = presetVar.body[bodyindex];
        if(data.data.bodys[bodyname] && data.data.bodys[bodyname].rows){
            data.data.bodys[bodyname].rows.forEach((row) => {
                let bodyValues = row.values;
                for (let attrcode in bodyValues) {
                    meta[bodyname].items.forEach((item) => {
                        if (item.attrcode == attrcode) {
                            item.initialvalue = {
                                value: bodyValues[attrcode].value,
                                display: bodyValues[attrcode].display = null ? bodyValues[attrcode].value : bodyValues[attrcode].display
                            };


                            //处理交叉校验规则和参照过滤
                            // let headValues = data.data.head[presetVar.head.head1].rows[0].values;
                            // filterAllRefParm(item, bodyValues, headValues);
                        }

                    });
                }
            });
        }
    });
}
function setbodyinitvalue(metas,headrows){
        //表头值变化后为表体元数据赋值
        // let headrows = data.head[presetVar.head.head1].rows[0].values;
        let headtrr = ['pk_org','pk_org_v','szxmid','pk_pcorg','pk_pcorg_v','pk_checkele','jobid','projecttask','pk_resacostcenter',
        'pk_proline','pk_brand','fctno','bzbm','tax_rate','bbhl','groupbbhl','globalbbhl','receiver','freecust','jkbxr',
        'dwbm','dwbm_v','skyhzh','custaccount','customer','deptid','deptid_v','paytarget','hbbm','fydeptid'];
        let cshare_detail = ['assume_org','assume_dept','pk_iobsclass'];//'fydwbm','fydeptid',
        // let metas  = props.meta.getMeta();
        //Object.keys(presetVar.body).forEach((bodyindex) =>{
        for (let bodyname in metas.gridrelation) {
            // let bodyname = presetVar.body[bodyindex];
            if(metas[bodyname].items!=undefined&&metas[bodyname].items!=null&&bodyname!='er_bxcontrast'&&bodyname!='accrued_verify'&&bodyname!='head'){
                metas[bodyname].items.forEach((item) => {
                    if (headtrr.indexOf(item.attrcode) > -1 || cshare_detail.indexOf(item.attrcode) > -1) {
                        let keycode = '';
                        if(item.attrcode=='assume_org'){
                            keycode = 'fydwbm';
                        }else if(item.attrcode=='assume_dept'){
                            //keycode = 'fydwbm';
							keycode = 'fydeptid';
                        }else if(item.attrcode=='pk_iobsclass'){
                            keycode = 'szxmid';
                        }else{
                            keycode = item.attrcode;
                        }
                        if(headrows[keycode]!=undefined && headrows[keycode].value!=undefined){
                            let valuecode = headrows[keycode].value==undefined?'':headrows[keycode].value;
                            let displaycode = headrows[keycode].display==undefined||headrows[keycode].display==''?'':headrows[keycode].display;
                            //当页面只有显示带版本的数据时不带版本的名称会没有值
                            if(displaycode==''||displaycode==null&&keycode.indexOf("_v")<0){
                                if(headrows[keycode+"_v"]!=undefined&&headrows[keycode+"_v"].display!=undefined&&headrows[keycode+"_v"].display!=null){
                                    displaycode = headrows[keycode+"_v"].display;
                                }else{
                                    if(valuecode!='' && valuecode!=null){
                                        //会导致值被清空，建议核实逻辑
                                        valuecode = valuecode;
                                        displaycode = valuecode;
                                    }else{
                                        valuecode = null;
                                        displaycode = null;
                                    }

                                }
                            }
                            // let initialvalue={
                            //     value: valuecode,
                            //     display: displaycode
                            // }
                            // item.initialvalue =initialvalue;
                        }
                    }
                });
            }
        };
}
function filterDatas(data){
    if(data==null){
        return {rows:[]}
    }
    let rows = data.rows;
    for(let i=0;i<rows.length;i++){
        if(rows[i].values==undefined){
            continue;
        }
        let values = rows[i].values;
        for(let item in values){
            if(item.indexOf('.')>-1&&values[item]!=undefined&&values[item]!=null){
            //    let itemp = item.substring(0,item.indexOf('.'));
               if(values[item].display==null||values[item].display==undefined||values[item].display==''){
                   values[item] = {value:null,display:null,scale:null};
               }else{
                  //元数据.属性不以参照形式显示直接显示名称.
                 values[item] = {value:values[item].display,display:values[item].display,scale:null};
               }
            }
        }
    }
    return data
}


function filterAllRefParm(item,props,moudleid){
    let PublicDefaultRefFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder';//公共
    let BusinessUnitTreeRefFilterPath ='nccloud.web.erm.action.ref.sqlbuilder.BusinessUnitTreeRefSqlBuilder';//组织
    let OrgTreeRefFilterPath ='nccloud.web.erm.action.ref.sqlbuilder.OrgTreeRefSqlBuilder';//组织
    let DeptClassTreeGridRef ='nccloud.web.erm.action.ref.sqlbuilder.DeptClassTreeGridRef';//部门
    let DeptTreeGridRef ='nccloud.web.erm.action.ref.sqlbuilder.DeptTreeGridRef';//部门
    let CurrtypeRefSqlFilterPath ='nccloud.web.erm.action.ref.sqlbuilder.CurrtypeRefSqlBuilder';//币种
    let PsndocClassFilterPath ='nccloud.web.erm.action.ref.sqlbuilder.PsndocClassTreeGridRef';//人员
    let PsndocTreeFilterPath ='nccloud.web.erm.action.ref.sqlbuilder.PsndocTreeGridRef';//人员
    let PsnbankaccRefSqlBuilder ='nccloud.web.erm.action.ref.sqlbuilder.PsnbankaccRefSqlBuilder';//个人银行账户
    let PsnbankaccTreeGridRef ='nccloud.web.erm.action.ref.sqlbuilder.PsnbankaccTreeGridRef';//个人银行账户
    let BankacctreeGridRef ='nccloud.web.erm.action.ref.sqlbuilder.BankacctreeGridRef';//个人银行账户
    let SupplierTreeGridRef ='nccloud.web.erm.action.ref.sqlbuilder.SupplierTreeGridRef';//供应商
    let ProjecTreetGridRef ='nccloud.web.erm.action.ref.sqlbuilder.ProjecTreetGridRef' ;//项目
    let CustomerTreeGridRef='nccloud.web.erm.action.ref.sqlbuilder.CustomerTreeGridRef';//客户
    let PublicDefaultGridRef='nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder';//公共
    const CustomerVersionTreeGridRef = 'nccloud.web.erm.action.ref.sqlbuilder.CustomerVersionTreeGridRef'
    const SupplierVersionGridRef =  'nccloud.web.erm.action.ref.sqlbuilder.SupplierVersionTreeGridRef'
    let filterold = item.referFilterAttr;
    let lengthArr = 1;
    if(filterold)
        lengthArr = filterold.length;
    let filter = new Array(lengthArr);
    if(filter){
        if(filter[item.attrcode]=="null"){
            filter[item.attrcode] ='';
        }else {

            if(filter[item.attrcode] && filter[item.attrcode].length>0)
            {filter[item.attrcode] = filter[item.attrcode].join(",");}
            else{filter[item.attrcode] ='';}
        }
    }else{filter ={};filter[item.attrcode] ='';}


      //所属组织，待确定是否需要特殊处理
    if (item.attrcode == 'pk_org') {
        item.queryCondition = () => {
            let paramurl = getRequest1(parent.window.location.hash);
            //如果没取到应用编码再取一下外层
            if(!paramurl.c){
                paramurl = getRequest1(parent.parent.window.location.hash);
            }
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value
            return {pk_group: data, TreeRefActionExt:OrgTreeRefFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y', appcode : paramurl.c}; // 根据pk_group过滤
        };
    }
    else if (item.attrcode == 'pk_org_v') {
        item.queryCondition = () => {
            let paramurl = getRequest1(parent.window.location.hash);
            //如果没取到应用编码再取一下外层
            if(!paramurl.c){
                paramurl = getRequest1(parent.parent.window.location.hash);
            }
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value
            return {pk_group: data, TreeRefActionExt:OrgTreeRefFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y', appcode : paramurl.c, isVerison : "Y"}; // 根据pk_group过滤
        };
    }
    //会计科目单独判断,没有预制字段
    else if(item.itemtype == 'refer' &&
                item.refcode === 'uapbd/refer/fiacc/AccountDefaultGridTreeRef/index') {
        const config = {}
        item.queryCondition = (p) => {
            var pkAccountingbook = null;
            // const pk_org = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'pk_org')))
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value   //直接取表头pk_org
            try {
                ajax({
                    url: '/nccloud/erm/ref/queryAccountBookAction.do',
                    data: { pk_org },
                    async: false,
                    loading:false,
                    success: (res) => {
                        if (res.success) {
                            pkAccountingbook = res.data;
                        }
                    },
                    error:(err)=>{
                        console.log('queryAccountBookAction err', err);
                    }
                })
            } catch (error) {
                console.log('queryAccountBookAction error:', error);
            }

            config.TreeRefActionExt = 'nccloud.web.arap.ref.before.CrossRuleSqlBuilder';
            config.UsualGridRefActionExt = 'nccloud.web.arap.ref.before.CrossRuleSqlBuilder';
            config.itemKey = 'subjcode';
            config.pk_org = pk_org;
            config.pk_accountingbook = pkAccountingbook;
            const billdate = props.form.getFormItemsValue(presetVar.head.head1, 'billdate')
            config.dateStr = billdate &&  billdate.value ? (props.form.getFormItemsValue(presetVar.head.head1, 'billdate').value).substring(0,10) : null;
            config.DataPowerOperationCode = 'fi';//使用权组
            return config;
        }
    }

    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='deptid'){
        //部门
        // item.refcode='uapbd/refer/org/DeptTreeRef/index'
        item.queryCondition = ()=>{
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['dwbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'dwbm')))

            return {pk_org: data,TreeRefActionExt:DeptTreeGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据apply_org过滤
        }
     }
     // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='deptid_v'){
        //部门
        // item.refcode='uapbd/refer/org/DeptTreeRef/index'
        item.queryCondition = ()=>{
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['dwbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'dwbm')))

            return {pk_org: data,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据apply_org过滤
        }
     }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='fydeptid'){
        //费用承担部门
        // item.refcode='uapbd/refer/org/DeptTreeRef/index'
        item.queryCondition = ()=>{
            //let data = dataValues['fydwbm']==null?"":dataValues['fydwbm'].value;
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'fydwbm')))
            return {pk_org: data,TreeRefActionExt:DeptTreeGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据apply_org过滤
        }
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='fydeptid_v'){
        //费用承担部门版本
        // item.refcode='uapbd/refer/org/DeptTreeRef/index'
        item.queryCondition = ()=>{
            //let data = dataValues['fydwbm']==null?"":dataValues['fydwbm'].value;
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'fydwbm')))
            return {pk_org: data,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据apply_org过滤
        }
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='assume_dept'){
        //费用承担部门
        //item.refcode='uapbd/refer/org/DeptTreeRef/index'
        item.queryCondition = ()=>{
            // let data = dataValues['assume_org']==null?"":dataValues['assume_org'].value;
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['assume_org'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'assume_org')))
            return {pk_org: data,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据apply_org过滤
        }
    }
    //收支项目
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if (item.attrcode == 'szxmid') {
       // item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/InoutBusiClassTreeRef.do";
        item.queryCondition = () => {
            // let data = dataValues['fydwbm']==null?"":dataValues['fydwbm'].value;
           let data  = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value;
            return {pk_org: data, TreeRefActionExt:PublicDefaultRefFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据assume_org过滤
        };
    }
    //收支项目
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if (item.attrcode == 'pk_iobsclass') {
        // item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/InoutBusiClassTreeRef.do";
         item.queryCondition = () => {
             // let data = dataValues['fydwbm']==null?"":dataValues['fydwbm'].value;
            let data = null
            if (moudleid=='er_cshare_detail'){
                const rowIndex = props.cardTable.getCurrentIndex(moudleid)
                data = props.cardTable.getRowsByIndexs(moudleid,rowIndex)[0].values['assume_org'].value
            }else{
                data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value
            }

            return {pk_org: data, DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据assume_org过滤
         };
     }
    // 供应商
    else if (item.attrcode == 'hbbm') {
        item.queryCondition = () => {
            let paytarget = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'paytarget')))
            if(paytarget&&paytarget!="1"){
                //收款对象为供应商
                return {pk_org: ''};
            }
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value
            return {pk_org:data, GridRefActionExt:SupplierTreeGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        };
    }
    // 供应商版本
    else if (item.attrcode == 'hbbm_v') {
        item.queryCondition = () => {
            let paytarget = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'paytarget')))
            if(paytarget&&paytarget!="1"){
                return {pk_org: ''};
            }
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value
            let date = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['djrq'].value
            return {pk_org:data, queryDate:date, GridRefActionExt:SupplierVersionGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        };
    }
    //客户
    else if (item.attrcode == 'customer') {
        item.queryCondition = () => {
            let paytarget = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'paytarget')))
            if(paytarget&&paytarget!="2"){
                //收款对象不是为客户， 供应商或员工
                return {pk_org: ''};
            }
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value
            return {pk_org: data, GridRefActionExt:CustomerTreeGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        };
    }
    //客户版本
    else if (item.attrcode == 'customer_v') {
        item.queryCondition = () => {
            let paytarget = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'paytarget')))
            if(paytarget&&paytarget != "2"){
                //收款对象不是为客户 供应商或员工
                return {pk_org: ''};
            }
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value
            let date = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['djrq'].value
            return {pk_org:data, queryDate:date, GridRefActionExt:CustomerVersionTreeGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        };
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='receiver'){
        //收款人
        item.queryCondition = ()=>{
            let paytarget = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'paytarget')))
            if(paytarget!="0"){
                return {tradetype:window.presetVar.tradetype,pk_dept: '',GridRefActionExt:PsndocTreeFilterPath};
            }
            let dwbm = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['dwbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'dwbm')))
            return {pk_org:dwbm,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据assume_org过滤
        }
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='skyhzh'){
        //个人银行账户
        item.queryCondition = ()=>{
            let pk_org = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'fydwbm')))
            let receiver = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['receiver'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'receiver')))
            //银行账户参照代码没接受人员信息？先返回空
            return { pk_org, pk_psndoc:receiver, GridRefActionExt:PsnbankaccTreeGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='fkyhzh'){
        //单位银行账户
       // item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/BankaccDefaultGridRef.do";
        item.queryCondition = ()=>{
            let pk_payorg = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_payorg'].value
            let bzbm = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['bzbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'bzbm')))
            //银行账户参照代码没接受人员信息？先返回空
            return {pk_org:pk_payorg,pk_currtype:bzbm,GridRefActionExt:BankacctreeGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='cashproj'){
        //资金计划项目
        item.queryCondition = ()=>{
            let pk_payorg = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_payorg'].value
            return {pk_org:pk_payorg,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        }
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='pk_cashaccount'){
        //现金账户
        //item.queryGridUrl=window.location.origin+"/nccloud/uapbd/sminfo/CashAccountGridRef.do";
        item.queryCondition = ()=>{
            let pk_payorg = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_payorg'].value
            let pk_group = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value;
            return {pk_org: pk_payorg,pk_group:pk_group,TreeRefActionExt:'',DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        }
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='cashitem'){
        //现金流量项目
        //item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/CashflowTreeRef.do";
        item.queryCondition = ()=>{
            let pk_payorg = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_payorg'].value
            let pk_group = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value;
            return {pk_org: pk_payorg,pk_group:pk_group,TreeRefActionExt:'',DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        }
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='freecust'){
        //散户
        item.queryCondition = ()=>{
            let paytarget = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'paytarget')))
            let customSupplier = '';
            if(paytarget=="0"){
                return {customSupplier:''};
            }else if(paytarget=="1"){
                // customSupplier = dataValues['hbbm']==null?"":dataValues['hbbm'].value;
                customSupplier = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['hbbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'hbbm')))

            }else if(paytarget=="2") {
                customSupplier = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['customer'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'customer')))
            }
           return {'pk_customsupplier':customSupplier,'customSupplier': customSupplier,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据pk_org过滤
        }
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='jobid'){
        //项目 --根据表头费用承担单位过滤
        item.queryCondition = ()=>{
            let pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['fydwbm'].value

            //银行账户参照代码没接受人员信息？先返回空
            return {pk_org:pk_org,GridRefActionExt:ProjecTreetGridRef,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    // //币种
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if (item.attrcode == 'bzbm') {
        // item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/InoutBusiClassTreeRef.do";
        item.queryCondition = () => {
            return {pk_currtype:filter[item.attrcode],TreeRefActionExt:CurrtypeRefSqlFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        };
    }
    // //人员
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if (item.attrcode == 'jkbxr') {
        item.queryCondition = () => {
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['dwbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'dwbm')))
            if(moudleid == presetVar.head.head1){
                return {tradetype:window.presetVar.tradetype,pk_org:data,org_id:data,GridRefActionExt:PsndocTreeFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据assume_org过滤
            }else{
                //新增业务报销单表体借款报销单人能参选到报销人单位下所有部门和人员
                return {pk_org:data,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据assume_org过滤
            }
            // return{};
        };
    }
    //报销事由
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if (item.attrcode == 'zy') {
        item.queryCondition = () => {
            let data = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['dwbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'dwbm')))
            return {pk_org: data,TreeRefActionExt:PsndocTreeFilterPath,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据assume_org过滤
        };
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='custaccount'){
        //客商银行账号
        item.queryCondition = ()=>{
            let accclass = "";
            let pk_cust = "";
            let paytarget = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['paytarget'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'paytarget')))
            if(paytarget=="1"){
                //收款对象为供应商
                accclass = "3";
                pk_cust = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['hbbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'hbbm')))

            } else if(paytarget=="2"){
                //收款对象为客户
                accclass = "1";
                pk_cust = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['customer'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'customer')))

            }
            let bzbm = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['bzbm'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'bzbm')))

            return { pk_cust: pk_cust,accclass:accclass,pk_currtype:bzbm,TreeRefActionExt:'',DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='pk_checkele'){
        //核算要素
        item.queryCondition = ()=>{
            let pk_org = (moudleid == presetVar.head.head1 ? (props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_pcorg'].value) : (getBodyValueBeforeRefRequest(props, moudleid, 'pk_pcorg')))

            return {pk_org: pk_org,TreeRefActionExt:'',DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if(item.attrcode=='pk_resacostcenter'){
        //成本中心
        item.queryCondition = ()=>{
            let pk_pcorg = ""
            let pk_group = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value
            let pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value
            if(moudleid == presetVar.head.head1) {
                pk_pcorg = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_pcorg'].value
            } else  {
                pk_pcorg = getBodyValueBeforeRefRequest(props, moudleid, 'pk_pcorg')

            }
            return {pk_org: pk_org,pk_group: pk_group,pk_profitcenter: pk_pcorg,TreeRefActionExt:'',DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    // //合同号
    // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
    else if (item.attrcode == 'fctno') {
        // item.queryGridUrl=window.location.origin+"/nccloud/uapbd/ref/InoutBusiClassTreeRef.do";
        item.queryCondition = () => {
            let pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value
            let bzbm =  getBodyValueBeforeRefRequest(props, moudleid, 'bzbm')
            let hbbm = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['hbbm'].value;
            return {GridRefActionExt:PublicDefaultGridRef,pk_org:pk_org,corigcurrencyid:bzbm,cvendorid:hbbm,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        };
    }

    //关联发票
    else if (item.attrcode == 'pk_erminvoice') {
        item.queryCondition = () => {
            let head_jkbxr = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['jkbxr'].value
            let body_jkbxr = getBodyValueBeforeRefRequest(props, moudleid, 'jkbxr')
            return {GridRefActionExt:PublicDefaultGridRef, pk_psndoc : body_jkbxr || head_jkbxr,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}
        }
    }else if (item.attrcode == 'pk_contractno') {
        item.queryCondition = () => {
            let pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            return {pk_org:pk_org,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }
    else if (item.attrcode == 'jsfs') {
        //结算方式
        item.queryCondition = () => {
            return {GridRefActionExt:'nccloud.web.erm.action.ref.sqlbuilder.BalatypeSqlBuilder', DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'};
        }
    }


    //处理交叉校验规则
    if (item.itemtype == 'refer') {
        let oldQueryCondition = item.queryCondition;
        let crossrule_itemkey = item.attrcode;
        item.queryCondition = (obj) => {
            let bodys = Object.values(window.presetVar.body);
            let bodyarr = [];
            let iscostshare = props.form.getFormItemsValue(presetVar.head.head1, 'iscostshare').value;
            if (iscostshare) {
                bodyarr = bodys;
            } else {
                bodys.forEach((one) => {
                    if (one != 'er_cshare_detail') {
                        bodyarr[bodyarr.length] = one;
                    }
                });
            }
            let crossrule_datasout = props.createExtCardData(props.meta.getMeta().code, 'head', bodyarr);
            let crossrule_tradetype = props.form.getFormItemsValue(presetVar.head.head1, 'djlxbm').value;
            let crossrule_org = props.form.getFormItemsValue(presetVar.head.head1, 'pk_org').value;
            let crossrule_datatypes = 'extbillcard';
            let isHead = moudleid == presetVar.head.head1 ? 'true' : 'false';

            let crossrule_datas = crossrule_datasout;
            if (moudleid != 'head' && window.presetVar.bodyChangeValuesAll != null) {
                if (
                    crossrule_datas.bodys[moudleid] != null &&
                    crossrule_datas.bodys[moudleid] != undefined &&
                    crossrule_datas.bodys[moudleid].rows != null
                ) {
                    crossrule_datas.bodys[moudleid].rows = [window.presetVar.bodyChangeValuesAll];
                }
            }
            let conditionFlag = true;
            if (oldQueryCondition == null || oldQueryCondition == undefined || oldQueryCondition == 'undefined') {
                conditionFlag = false;
            }

            let oldData = '';
            if (conditionFlag) {
                oldData = oldQueryCondition();
            }
            if (oldData == null || oldData == undefined || oldData == 'undefined') {
                oldData = '';
            }

            let config = {
                crossrule_datas: JSON.stringify(crossrule_datas),
                crossrule_tradetype: crossrule_tradetype,
                crossrule_org: crossrule_org,
                crossrule_datatypes: crossrule_datatypes,
                crossrule_area: moudleid,
                crossrule_itemkey: crossrule_itemkey,
                crossrule_isHead: isHead,
                ...oldData
            };

            //参照类型的自定义项字段增加组织过滤
            if (
                !oldData.pk_org &&
                obj &&
                obj.attrcode &&
                (obj.attrcode.startsWith('defitem') || obj.attrcode.startsWith('zyx') || obj.datatype == '56')
            ) {
                config.pk_org = crossrule_org;
            }

            if (obj == undefined || obj == null || obj.refType == undefined || obj.refType == null) {
                if (
                    config.TreeRefActionExt == null ||
                    config.TreeRefActionExt == undefined ||
                    config.TreeRefActionExt.length == 0
                ) {
                    config.TreeRefActionExt = PublicDefaultGridRef;
                }
                return config;
            }

            if (obj.refType == 'grid') {
                if (
                    config.GridRefActionExt == null ||
                    config.GridRefActionExt == undefined ||
                    config.GridRefActionExt.length == 0
                ) {
                    config.GridRefActionExt = PublicDefaultGridRef;
                }
            } else if (obj.refType == 'tree') {
                if (
                    config.TreeRefActionExt == null ||
                    config.TreeRefActionExt == undefined ||
                    config.TreeRefActionExt.length == 0
                ) {
                    config.TreeRefActionExt = PublicDefaultGridRef;
                }
            } else if (obj.refType == 'gridTree') {
                if (
                    config.GridRefActionExt == null ||
                    config.GridRefActionExt == undefined ||
                    config.GridRefActionExt.length == 0
                ) {
                    config.GridRefActionExt = PublicDefaultGridRef;
                }
            }

            return config;
        };
    }

}
export default  requestApiOverwrite;

/**
 * 表体参照请求前获取表体行某字段的值
 * @param {} props
 */
function getBodyValueBeforeRefRequest(props, tablecode, key){
    let clickRow = props.cardTable.getClickRowIndex(tablecode)
    if (clickRow){
        if(clickRow.record.values[key]) {
            return clickRow.record.values[key].value;
        } else {
            // toast({content:`表体模板没有配置${key}字段`, color:'danger'})
        }
    }else{
        let currentIndex = props.cardTable.getCurrentIndex(tablecode);
        return props.cardTable.getDataByIndex(tablecode, currentIndex).values[key].value;
    }

}

